///*
// * Copyright 2025 The Android BYOD Project
// */
//
//package com.example.testble;
//
//import android.annotation.SuppressLint;
//import android.bluetooth.BluetoothAdapter;
//import android.bluetooth.BluetoothDevice;
//import android.bluetooth.BluetoothGatt;
//import android.bluetooth.BluetoothGattCharacteristic;
//import android.bluetooth.BluetoothGattDescriptor;
//import android.bluetooth.BluetoothGattServer;
//import android.bluetooth.BluetoothGattServerCallback;
//import android.bluetooth.BluetoothGattService;
//import android.bluetooth.BluetoothManager;
//import android.bluetooth.BluetoothProfile;
//import android.bluetooth.le.AdvertiseCallback;
//import android.bluetooth.le.AdvertiseData;
//import android.bluetooth.le.AdvertiseSettings;
//import android.bluetooth.le.BluetoothLeAdvertiser;
//import android.content.Context;
//import android.os.Build;
//import android.os.ParcelUuid;
//import android.text.TextUtils;
//import android.util.Log;
//
//import androidx.annotation.NonNull;
//import androidx.annotation.RequiresApi;
//import androidx.annotation.VisibleForTesting;
//
//
//import org.json.JSONException;
//import org.json.JSONObject;
//
//import java.nio.charset.StandardCharsets;
//import java.security.SecureRandom;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.Set;
//import java.util.UUID;
//
///** GattAuthServer */
//@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//public class GattAuthServer extends BluetoothGattServerCallback implements TestHelper {
//
//    private static final String TAG = "BluetoothGattAuthServer";
//
//    private BluetoothManager bluetoothManager;
//    private BluetoothGattServer gattServer;
//    private BluetoothAdapter bluetoothAdapter;
//    private BluetoothLeAdvertiser advertiser;
//    private AdvertiseCallback advertiseCallback;
//
//    public static UUID UUID_SERVICE = UUID.fromString("0000a000-0000-1000-8000-00805f9b34fb");
//    public static UUID UUID_CHALLENGE = UUID.fromString("0000a001-0000-1000-8000-00805f9b34fb");
//    public static UUID UUID_AUTH = UUID.fromString("0000a002-0000-1000-8000-00805f9b34fb");
//    private static final UUID DESCRIPTOR_UUID_CHALLENGE =
//            UUID.fromString("0000b001-0000-1000-8000-00805f9b34fb");
//    private static final UUID DESCRIPTOR_UUID_AUTH =
//            UUID.fromString("0000b002-0000-1000-8000-00805f9b34fb");
//    private final Map<String, byte[]> pendingChallenges = new HashMap<>(); // address -> challenge
//    private final Map<String, String> connectedDevices = new HashMap<>(); // token -> address
//    private AdvertiseSettings advertiseSettings;
//    private AdvertiseData advertiseData;
//    private Context context;
//
//    @SuppressLint("MissingPermission")
//    public GattAuthServer(Context context) {
//        this.context = context;
//
//        this.initBluetoothAdapter();
//
//        UUID_SERVICE = UUID.randomUUID();
//        BLogger.d(TAG, "UUID_SERVICE :" + UUID_SERVICE.toString());
//        UUID_CHALLENGE = UUID.randomUUID();
//        BLogger.d(TAG, "UUID_CHALLENGE :" + UUID_CHALLENGE.toString());
//        UUID_AUTH = UUID.randomUUID();
//        BLogger.d(TAG, "UUID_AUTH :" + UUID_AUTH.toString());
//
//        bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
//        bluetoothAdapter = bluetoothManager.getAdapter();
//        gattServer = bluetoothManager.openGattServer(context, this);
//        BluetoothGattService service = getBluetoothGattService();
//        gattServer.addService(service);
//        // init BLE advertiser
//        advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
//        if (advertiser == null) {
//            BLogger.e(TAG, "start failure, advertiser is null");
//            return;
//        }
//
//        advertiseSettings =
//                new AdvertiseSettings.Builder()
//                        .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
//                        .setConnectable(true)
//                        .setTimeout(0)
//                        .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
//                        .build();
//
//        ParcelUuid pUuid = new ParcelUuid(UUID_SERVICE);
//
//        advertiseData =
//                new AdvertiseData.Builder()
//                        .setIncludeDeviceName(false)
//                        .addServiceUuid(pUuid)
//                        .build();
//
//        //        advertiseCallback = new AdvertiseCallback() {
//        //            @Override
//        //            public void onStartSuccess(AdvertiseSettings settingsInEffect) {
//        //                BLogger.i(TAG, "BLE Advertise success");
//        //            }
//        //
//        //            @Override
//        //            public void onStartFailure(int errorCode) {
//        //                BLogger.e(TAG, "BLE Advertise failure，errorCode: " + errorCode);
//        //            }
//        //        };
//    }
//
//    @NonNull
//    public static BluetoothGattService getBluetoothGattService() {
//        BluetoothGattService service =
//                new BluetoothGattService(UUID_SERVICE, BluetoothGattService.SERVICE_TYPE_PRIMARY);
//        BluetoothGattCharacteristic challengeChar =
//                new BluetoothGattCharacteristic(
//                        UUID_CHALLENGE,
//                        BluetoothGattCharacteristic.PROPERTY_READ,
//                        BluetoothGattCharacteristic.PERMISSION_READ);
//        BluetoothGattDescriptor challengeDesc =
//                new BluetoothGattDescriptor(
//                        DESCRIPTOR_UUID_CHALLENGE, BluetoothGattDescriptor.PERMISSION_READ);
//        challengeChar.addDescriptor(challengeDesc);
//        BluetoothGattCharacteristic authChar =
//                new BluetoothGattCharacteristic(
//                        UUID_AUTH,
//                        BluetoothGattCharacteristic.PROPERTY_WRITE,
//                        BluetoothGattCharacteristic.PERMISSION_WRITE);
//        BluetoothGattDescriptor authDesc =
//                new BluetoothGattDescriptor(
//                        DESCRIPTOR_UUID_AUTH, BluetoothGattDescriptor.PERMISSION_READ);
//        authChar.addDescriptor(authDesc);
//        service.addCharacteristic(challengeChar);
//        service.addCharacteristic(authChar);
//        return service;
//    }
//
//    @SuppressLint("MissingPermission")
//    public void start() {
//        if (advertiseSettings != null) {
//            if (advertiseCallback == null) {
//                advertiseCallback =
//                        new AdvertiseCallback() {
//                            @Override
//                            public void onStartSuccess(AdvertiseSettings settingsInEffect) {
//                                BLogger.i(TAG, "BLE Advertise success");
//                            }
//
//                            @Override
//                            public void onStartFailure(int errorCode) {
//                                BLogger.e(TAG, "BLE Advertise failure，errorCode: " + errorCode);
//                            }
//                        };
//                advertiser.startAdvertising(advertiseSettings, advertiseData, advertiseCallback);
//            }
//        }
//    }
//
//    @SuppressLint("MissingPermission")
//    public void stop() {
//        if (advertiser != null && advertiseCallback != null) {
//            advertiser.stopAdvertising(advertiseCallback);
//            advertiseCallback = null;
//        }
//        //        if (gattServer != null) {
//        //            gattServer.close();
//        //            gattServer = null;
//        //        }
//        //        pendingChallenges.clear();
//        //        connectedDevices.clear();
//    }
//
//    @VisibleForTesting
//    @Override
//    public Map<String, byte[]> getPendingChallenges() {
//        return pendingChallenges;
//    }
//
//    @VisibleForTesting
//    @Override
//    public Map<String, String> getConnectedDevices() {
//        return connectedDevices;
//    }
//
//    @Override
//    public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
//        if (newState == BluetoothProfile.STATE_CONNECTED) {
//            byte[] challenge = new byte[16];
//            new SecureRandom().nextBytes(challenge);
//            pendingChallenges.put(device.getAddress(), challenge);
//            BLogger.d(TAG, "Device connected: " + device.getAddress());
//        } else {
//            pendingChallenges.remove(device.getAddress());
//            BLogger.d(TAG, "Device disconnected: " + device.getAddress());
//        }
//    }
//
//    @SuppressLint("MissingPermission")
//    @Override
//    public void onCharacteristicReadRequest(
//            BluetoothDevice device,
//            int requestId,
//            int offset,
//            BluetoothGattCharacteristic characteristic) {
//        if (UUID_CHALLENGE.equals(characteristic.getUuid())) {
//            byte[] challenge = pendingChallenges.get(device.getAddress());
//            if (challenge != null) {
//                gattServer.sendResponse(
//                        device, requestId, BluetoothGatt.GATT_SUCCESS, 0, challenge);
//                BLogger.d(TAG, "onCharacteristicReadRequest====== device: " + device.toString() + " challenge: " + challenge);
//            } else {
//                gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
//            }
//        }
//    }
//
//    @SuppressLint("MissingPermission")
//    @Override
//    public void onCharacteristicWriteRequest(
//            BluetoothDevice device,
//            int requestId,
//            BluetoothGattCharacteristic characteristic,
//            boolean preparedWrite,
//            boolean responseNeeded,
//            int offset,
//            byte[] value) {
//
//        if (UUID_AUTH.equals(characteristic.getUuid())) {
//
//            // 使用加密传输数据
//            //String jsonStr = AESUtil.decrypt(new String(value, StandardCharsets.UTF_8));
//
//            String jsonStr = new String(value, StandardCharsets.UTF_8);
//
//            BLogger.d(TAG, "onCharacteristicWriteRequest====== device: " + device.toString() + " BoundType: " + device.getBondState() + " value: " + jsonStr);
//
//            try {
//                JSONObject obj = new JSONObject(jsonStr);
//                String token = obj.getString("token");
//                String address = device.getAddress();
//                String name = device.getName();
//                String id = obj.getString("token");
//                boolean check = checkBtMacIsPaired(address);
//
//                if (!check) {
//                    String bleAddress = getCacheAddress(id);
//                    if (bleAddress != null && !bleAddress.trim().isEmpty()) {
//                        BLogger.d(TAG, "onCharacteristicWriteRequest====== mac地址无法校验通过, 使用之前已通过的mac地址尝试" + "input address :" + address + "saved address : " + bleAddress);
//                        address = bleAddress;
//                        check = checkBtMacIsPaired(address);
//                    }
//                }
//
//                ByodDeviceInfo deviceInfo = new ByodDeviceInfo();
//                deviceInfo.setBtAddress(address);
//                deviceInfo.setBtName(name);
//                deviceInfo.setBtPaired(check);
//                deviceInfo.setDeviceId(id);
////                Cache.getInstance().putBtPairedId(id, deviceInfo);
//                if (check) {
//                    setCacheAddress(id,address);
//                }
//                BLogger.d(TAG, "onScan ios result:" + deviceInfo.toString());
//                connectedDevices.put(token, device.getAddress());
//                if (responseNeeded) {
//                    BLogger.d(TAG, "gattServer sendResponse check:" + check);
//                    gattServer.sendResponse(
//                            device,
//                            requestId,
//                            check ? BluetoothGatt.GATT_SUCCESS : BluetoothGatt.GATT_FAILURE,
//                            0,
//                            null);
//                }
//            } catch (JSONException e) {
//                BLogger.e(TAG, "JSONException" + e);
//                gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
//            }
//        }
//    }
//
//    @SuppressLint("MissingPermission")
//    public boolean checkBtMacIsPaired(String address) {
//        BLogger.d(TAG, "checkBtMacIsPaired: [" + address + "]");
//        Set<BluetoothDevice> bluetoothDeviceSet = getBluetoothAdapter().getBondedDevices();
//        if (bluetoothDeviceSet != null) {
//            Object[] bluetoothDevices = bluetoothDeviceSet.toArray();
//            for (Object o : bluetoothDevices) {
//                BluetoothDevice bluetoothDevice = (BluetoothDevice) o;
//                BLogger.d(
//                        TAG,
//                        "checkBtMacIsPaired bluetoothDevice: "
//                                + bluetoothDevice.getAddress()
//                                + ","
//                                + bluetoothDevice.getName());
//                if (TextUtils.equals(address, bluetoothDevice.getAddress())) {
//                    return true;
//                }
//            }
//        }
//        return false;
//    }
//
//    public void init() {
//        Log.d(TAG, "init: ");
//        initBluetoothAdapter();
//    }
//
//    private void initBluetoothAdapter() {
//        bluetoothManager =
//                (BluetoothManager)
//                       this.context
//                                .getSystemService(Context.BLUETOOTH_SERVICE);
//        bluetoothAdapter = bluetoothManager.getAdapter();
//    }
//
//    protected BluetoothAdapter getBluetoothAdapter() {
//        return bluetoothAdapter;
//    }
//
//
//    // ******************************************************
//
//    private static final String Device_ID_Prefix = "BYOD_IOS_DEVICE_";
//
//    private String getCacheAddress(String deviceId) {
//        return SharedPrefsUtils.getString(this.context, Device_ID_Prefix + deviceId);
//    }
//
//    private void setCacheAddress(String deviceId, String bleAddress) {
//        if(!bleAddress.equals(getCacheAddress(deviceId))) {
//            SharedPrefsUtils.saveString(this.context, Device_ID_Prefix + deviceId, bleAddress);
//        }
//    }
//
//
//}
//
//interface TestHelper {
//    @VisibleForTesting
//    Map<String, byte[]> getPendingChallenges();
//
//    @VisibleForTesting
//    Map<String, String> getConnectedDevices();
//}
